/* typehints:start */
import { Application } from "../application";
/* typehints:end */

import { People } from "./people";
import { createLogger } from "../core/utils/logging";
import { GameRoot } from "./root";
import { GameHUD } from "./huds/hud";
import { Time } from "./time";
import { WorldMap } from "./maps/world_map";
import { GameEvent } from "./game_event";
import { GameTask } from "./task/game_task";
import { matchArray } from "../core/utils/utils";
import { BackDrop } from "./backdrop";
import { BattleManager } from "./battle/battle_manager";
import { globalConfig } from "../config/global";
import { Player } from "./people/player";

const logger = createLogger('game/core')

export class GameCore{
  constructor(app){
    /** @type {Application} */
    this.app = app;
  }

  initializeRoot(parentState){
    logger.log('初始化游戏根数据');
    console.time('⏰ 初始游戏根数据耗时');

    this.root = new GameRoot(this.app);
    this.root.gameState = parentState;
    this.root.savegame = this.app.savegame;
    this.root.itemData = this.app.savegame.getItemData();
    this.root.worldData = this.app.savegame.getWorldData();
    this.root.sundryData = this.app.savegame.getSundryData();
    this.root.playerData = this.app.savegame.getPlayerData();

    this.transformPlayerData();

    this.root.mainPlayer = this.root.findPlayerPeople(globalConfig.player._id);
    const root = this.root;

    this.root.time = new Time(root);

    console.time('⏰ 地图文件解析耗时');
    this.root.worldMap = new WorldMap(root);
    this.root.worldMap.initialize();
    console.timeEnd('⏰ 地图文件解析耗时');
    
    this.root.event = new GameEvent(root);
    this.root.event.initialize();

    this.root.task = new GameTask(root);
    this.root.task.initialize();

    this.root.backdrop = new BackDrop(root);
    this.root.backdrop.initialize();

    this.root.hud = new GameHUD(root);
    this.root.hud.initialize();

    this.root.battleMgr = new BattleManager(root);
    this.root.battleMgr.initialize();

    console.timeEnd('⏰ 初始游戏根数据耗时')
    logger.log('✅ 游戏根数据初始化完成');
  }

  transformPlayerData(){
    this.root.playerData.troops = this.root.playerData.troops.map(item => {
      if(item._id == globalConfig.player._id){
        return new Player(this.root, item);
      }
      return new People(this.root, item);
    })
  }

  onResized(width, height){
    if(this.root.hud){
      this.root.hud.signals.resized.dispatch(width, height);
    }
  }

  update(dt){
    if (this.root.time) {
      this.root.time.update(dt);
    }
    
    if(this.root.gamePlay){
      if (this.root.hud) {
        this.root.hud.update(dt);
      }

      if (this.root.worldMap) {
        this.root.worldMap.update(dt);
      }

      // 为玩家对象每帧执行
      this.root.mainPlayer.update();
    }
    if(this.root.battlePlay){
      if(this.root.battleMgr){
        this.root.battleMgr.update();
      }
    }
  }

  destruct(){
    this.root.destruct();
    delete this.root;
    this.root = null;
    this.app = null;
  }
}